const request = require('request')
const axios = require('axios')
const express = require('express')
const router = express.Router()

async function get_token() {
  // 1.获取token
  const tokenOption = {
    'method': 'POST',
    'url': 'https://aip.baidubce.com/oauth/2.0/token?client_id=9PKkuARdRKEItAWVD8rXXKXc&client_secret=K0tAD4o2xVEGPa7dUfhMwNk4prP6Fx6N&grant_type=client_credentials',
    'headers': {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }

  const token = await axios(tokenOption)

  return token.data.access_token
}

router.get('/', async (req, res) => {
  const taskId = req.body.taskId

  // 3.查询图片
  const queryImage = await axios.post(
    'https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImg?access_token=' + await get_token(),
    {
      taskId
    }
  )

  res.send(JSON.stringify({
    img: queryImage.data.data.img
  }))
})

router.post('/', async (req, res) => {
  const text = req.body.text
  const style = req.body.style

  // 2.提交生成图片的请求
  const resultReq = await axios.post(
    'https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img?access_token=' + await get_token(),
    {
      text,
      resolution: "1024*1024",
      style
    }
  )

  res.send(JSON.stringify({
    taskId: resultReq.data.data.taskId
  }))
})

module.exports = router